//
//  PictureSelectorViewController.swift
//  Weibo
//
//  Created by 周先生 on 15/11/21.
//  Copyright © 2015年 周先生. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let column: CGFloat = 4
private let pictureCellMargin: CGFloat = 10
private let maxImageCount = 3
class PictureSelectorViewController: UICollectionViewController {
    
    //添加图片数组属性
     lazy var imageList = [UIImage]()

    init() {
        let layout = UICollectionViewFlowLayout()
        //设置layoout
        let w = (screenW - (column + 1) * pictureCellMargin) / column
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        //设置section间距
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        //
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)


    }


    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        let delta = (imageList.count == maxImageCount) ? 0 : 1
        return delta + imageList.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
    
        cell.backgroundColor = UIColor.randomColor()
        //设置代理
        cell.selectorCellDelegate = self
        
        //绑定数据
        if indexPath.item == imageList.count {
            cell.image = nil
        
        }else {
            cell.image = imageList[indexPath.item]
        
        }
        
        return cell
    }

    // MARK: UICollectionViewDelegate


}

//
extension PictureSelectorViewController: PictureSelectorCellDelegate{
    func userWillAddPicture(cell: PictureSelectorCell) {
//        print("添加图片")
        if cell.image != nil {  //保证添加的数量
            print("已经添加图片")
            return
        }
        //使用系统的图片选择器
        let picker = UIImagePickerController()
        //指定代理
        picker.delegate = self
        //设置是否允许编辑 在上头像的时候需要打开
//        picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
    }
    func userWillDeletePicture(cell: PictureSelectorCell) {
        print("删除图片")
        //获取点击cell的indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
        self.imageList.removeAtIndex(indexPath!.item)
        
        //刷新视图
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            cell.alpha = 0
            }) { (_) -> Void in
                cell.alpha = 1
                self.collectionView?.reloadData()
        }
    }

}
//遵守图片选择器的协议
extension PictureSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print(image)
//        print(editingInfo)
        
        //添加图片
        imageList.append(image)
        //刷新集合视图
        collectionView?.reloadData()
        //一旦实现协议方法 dismiss就交给程序员
        dismissViewControllerAnimated(true, completion: nil)
    }

}
//定义协议
@objc protocol PictureSelectorCellDelegate: NSObjectProtocol {
    //定义协议方法
    //添加图片的协议方法
    optional func userWillAddPicture(cell: PictureSelectorCell)
    //删除图片的协议方法
    optional func userWillDeletePicture(cell: PictureSelectorCell)


}
class PictureSelectorCell: UICollectionViewCell {

    //定义代理
    weak var selectorCellDelegate: PictureSelectorCellDelegate?
    @objc func addBtnDidClick() {
        selectorCellDelegate?.userWillAddPicture?(self)
    
    }
    @objc func deleteBtnDidClick() {
        selectorCellDelegate?.userWillDeletePicture?(self)
    
    }
    //定义图片数据模型
    var image: UIImage? {
    
        didSet {
        deleteBtn.hidden = (image == nil)
            if image != nil {
                addBtn.setBackgroundImage(image, forState: .Normal)
            
            }else {
            
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            
            }
        }
    
    }
    

    //3,重写父类构造方法 调用设置UI
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //2,设置UI
    private func setupUI() {
        //添加子控件
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.top.equalTo(contentView)
        }
        //添加点击事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
    
    }
    //1,懒加载子控件compose_pic_add
    private lazy var addBtn: UIButton = UIButton(title: nil, backImage: "compose_pic_add", color: nil)
    private lazy var deleteBtn: UIButton = UIButton(title: nil, backImage: "compose_photo_close", color: nil)
}